<template>
  <el-dialog
    v-model="visible"
    :title="`客户 ${customerName} 的订单`"
    width="80%"
    class="customer-orders-dialog"
    @close="handleClose"
  >
    <div class="dialog-content">
      <!-- 统计信息 -->
      <div class="stats-container">
        <el-card shadow="never" class="stats-card">
          <div class="stat-item">
            <span class="label">订单总数：</span>
            <span class="value">{{ orderStats.total }}</span>
          </div>
          <div class="stat-item">
            <span class="label">订单总金额：</span>
            <span class="value">{{ formatCurrency(orderStats.totalAmount) }}</span>
          </div>
          <div class="stat-item">
            <span class="label">最近订单日期：</span>
            <span class="value">{{ orderStats.lastOrderDate ? formatDate(orderStats.lastOrderDate) : '-' }}</span>
          </div>
        </el-card>
      </div>

      <!-- 订单表格 -->
      <div class="table-container">
        <el-table
          :data="orders"
          v-loading="loading"
          stripe
          style="width: 100%"
          @row-click="viewOrderDetail"
        >
          <el-table-column prop="platformOrderId" label="订单号" width="150" />
          <el-table-column prop="orderAmount" label="订单金额" width="120">
            <template #default="{ row }">
              {{ formatCurrency(row.orderAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="orderDate" label="订单日期" width="120">
            <template #default="{ row }">
              {{ formatDate(row.orderDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="订单状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getOrderStatusType(row.orderStatus)">
                {{ getOrderStatusText(row.orderStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="invoiceStatus" label="发票状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getInvoiceStatusType(row.invoiceStatus)">
                {{ getInvoiceStatusText(row.invoiceStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="responsibleSalesman" label="销售人员" width="120" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button type="primary" link @click="viewOrderDetail(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 订单详情对话框 -->
  <el-dialog
    v-model="orderDetailVisible"
    title="订单详情"
    width="800px"
    class="order-detail-dialog"
  >
    <div class="order-detail" v-if="selectedOrder">
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions :column="2" border class="detail-descriptions">
            <el-descriptions-item label="订单号" :span="2">
              {{ selectedOrder.platformOrderId }}
            </el-descriptions-item>
            <el-descriptions-item label="订单金额">
              {{ formatCurrency(selectedOrder.orderAmount) }}
            </el-descriptions-item>
            <el-descriptions-item label="订单日期">
              {{ formatDate(selectedOrder.orderDate) }}
            </el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getOrderStatusType(selectedOrder.orderStatus)" class="status-tag">
                {{ getOrderStatusText(selectedOrder.orderStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="销售人员">
              {{ selectedOrder.responsibleSalesman || '未分配' }}
            </el-descriptions-item>
            <el-descriptions-item label="发票状态">
              <el-tag :type="getInvoiceStatusType(selectedOrder.invoiceStatus)" class="status-tag">
                {{ getInvoiceStatusText(selectedOrder.invoiceStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="发票号码" v-if="selectedOrder.invoiceNumber">
              {{ selectedOrder.invoiceNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="发票日期" v-if="selectedOrder.invoiceDate">
              {{ formatDate(selectedOrder.invoiceDate) }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="orderDetailVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { customerAPI } from '@/api/customer'
import { getSalesOrderDetail } from '@/api/sales'

interface SalesOrder {
  id: number
  platformOrderId: string
  customerId: number
  orderAmount: number
  orderDate: string
  invoiceStatus: string
  invoiceDate: string | null
  invoiceNumber: string | null
  orderStatus: string
  responsibleSalesman: string | null
}

interface Props {
  modelValue: boolean
  customerId: string
  customerName: string
}

interface OrderStats {
  total: number
  totalAmount: number
  lastOrderDate: string | null
}

const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const orders = ref<SalesOrder[]>([])
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const orderStats = ref<OrderStats>({
  total: 0,
  totalAmount: 0,
  lastOrderDate: null
})

// 订单详情相关状态
const orderDetailVisible = ref(false)
const selectedOrder = ref<SalesOrder | null>(null)
const activeTab = ref('basic')

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newValue: boolean) => {
    visible.value = newValue
    if (newValue) {
      loadOrders()
    }
  }
)

// 监听visible变化
watch(visible, (newValue: boolean) => {
  emit('update:modelValue', newValue)
})

// 格式化货币
const formatCurrency = (amount: number) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2
  }).format(amount)
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 获取订单状态类型
const getOrderStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': 'warning',
    'paid': 'success',
    'shipped': 'primary',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取订单状态文本
const getOrderStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': '待付款',
    'paid': '已付款',
    'shipped': '已发货',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 获取发票状态类型
const getInvoiceStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'uninvoiced': 'info',
    'invoiced': 'warning',
    'sent': 'success'
  }
  return statusMap[status] || 'info'
}

// 获取发票状态文本
const getInvoiceStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'uninvoiced': '未开票',
    'invoiced': '已开票',
    'sent': '已发送'
  }
  return statusMap[status] || status
}

// 加载订单数据
const loadOrders = async () => {
  loading.value = true
  try {
    const params = {
      customerId: props.customerId,
      page: pagination.value.currentPage,
      limit: pagination.value.pageSize
    }
    
    const response = await customerAPI.getCustomerOrders(params)
    
    if (response.success) {
      orders.value = response.data.list
      pagination.value.total = response.data.pagination.total
      
      // 更新统计信息
      orderStats.value = {
        total: response.data.stats.totalOrders,
        totalAmount: response.data.stats.totalAmount,
        lastOrderDate: response.data.stats.lastOrderDate
      }
    } else {
      ElMessage.error(response.message || '获取订单列表失败')
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 查看订单详情
const viewOrderDetail = async (order: SalesOrder) => {
  try {
    const response = await getSalesOrderDetail(order.id)
    if (response.data) {
      selectedOrder.value = response.data
      orderDetailVisible.value = true
    } else {
      ElMessage.error('获取订单详情失败')
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败: ' + (error as Error).message)
  }
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  loadOrders()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  pagination.value.currentPage = page
  loadOrders()
}

// 处理关闭
const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.customer-orders-dialog {
  .dialog-content {
    max-height: 70vh;
    overflow-y: auto;
  }
  
  .stats-container {
    margin-bottom: 20px;
    
    .stats-card {
      :deep(.el-card__body) {
        display: flex;
        justify-content: space-around;
        align-items: center;
        flex-wrap: wrap;
        gap: 20px;
      }
      
      .stat-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .label {
          font-size: 14px;
          color: #606266;
          margin-bottom: 4px;
        }
        
        .value {
          font-size: 18px;
          font-weight: bold;
          color: #303133;
        }
      }
    }
  }
  
  .table-container {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}

.order-detail-dialog {
  .detail-tabs {
    :deep(.el-tabs__content) {
      padding: 20px 0;
    }
  }
  
  .detail-descriptions {
    :deep(.el-descriptions__label) {
      width: 120px !important;
    }
  }
  
  .status-tag {
    margin-right: 8px;
  }
  
  .collection-result {
    .result-header {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .label {
        font-weight: bold;
        color: #606266;
      }
      
      .value {
        color: #303133;
      }
    }
  }
  
  .no-collection {
    text-align: center;
    padding: 40px 0;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>